<?php
namespace app\common\model;
use think\Model;
use think\DB;
class Member extends Model{
	// 定义时间戳字段名
	protected $createTime = '';
	protected $updateTime = '';	
	// 自动完成
	protected $insert = ['member_reg_time','member_last_login_time','member_nickname','member_reg_ip','member_last_login_ip','member_status'=>1];	//新增
	protected $update = ['member_last_login_ip','member_last_login_time'];	//更新
	protected function setMemberRegTimeAttr($value){
		return time();
	}
	protected function setMemberLastLoginTimeAttr($value){
		return time();
	}		
    protected function setMemberNicknameAttr($value,$data){
        return !$value ? $value:$data['member_name'];
    }	
    protected function setMemberRegIpAttr(){
        return ip2long(request()->ip());
    }
	protected function setMemberLastLoginIpAttr(){
		return ip2long(request()->ip());
	}	
	protected function setMemberPasswordAttr($value,$data){
		return md5(md5($value).$data['member_salt']);
	}
	public function login($username = '', $password = '', $type = 1){
		if(empty($username) || empty($password)){
			$this->error = '用户名或密码为空';
			return false;
		}		
		$map = array();
		if (\think\Validate::is($username,'email')) {
			$type = 2;
		} elseif (preg_match("/^1[34578]{1}\d{9}$/",$username)){
			$type = 3;
		}
		switch ($type) {
			case 1:
				$map['member_name'] = $username;
				break;
			case 2:
				$map['member_email'] = $username;
				break;
			case 3:
				$map['member_mobile'] = $username;
				break;
			case 4:
				$map['member_id'] = $username;
				break;
			default:
				$this->error = '参数错误';
			    return false;
		}
		if(empty($map)){
			$this->error = '参数错误';
			return false;			
		}
		$user = $this->where($map)->find();
		if($user['member_id']){
		    if($user['member_status']==0){
			    $this->error = '帐号已锁定';
			    return false;
		    }			
			if(md5(md5($password).$user['member_salt']) === $user['member_password']) {
				$this->autoLogin($user); //更新用户登录信息
				return $user; //登录成功，返回用户信息
			}else{
			    $this->error = '密码错误';
			    return false;
		    }				
		}else{
			$this->error = '用户不存在';
			return false;
		}
	}
	function register($data){
		$data['member_salt'] = rand_string(8);
		if($this->validate('member.add')->save($data)!== false){
			return 1;
		}else{
			if (!$this->getError()) {
				$this->error = $this->getError();
			}
			return false;
		}
	}
	public function editUser($data, $ischangepwd = false){
		if ($data['member_id']) {
			if (!$ischangepwd || ($ischangepwd && $data['member_password'] == '')) {
				unset($data['member_salt']);
				unset($data['member_password']);
			}else{
				$data['member_salt'] = rand_string(8);
			}
			if($this->validate('member.edit')->save($data,array('member_id'=>$data['member_id']))!== false){
				return 1;
			}else{
			    if(!$this->getError()) {
				    $this->error = $this->getError();
			    }
				return false;
			}
		}else{
			$this->error = "非法操作！";
			return false;
		}
	}
	public function editpw($data, $is_reset = false){
		$user_id = $is_reset ? $data['member_id'] : session('member_auth.member_id');
		if (!$is_reset) {
			//后台修改用户时可修改用户密码时设置为true
			$checkPassword=$this->checkPassword($user_id,$data['oldpassword']);
			$validate = $this->validate('member.password');
			if (false === $validate || false === $checkPassword) {
				return false;
			}
		}
		$data['member_salt'] = rand_string(8);
		return $this->save($data, array('member_id'=>$user_id));
	}

	protected function checkPassword($user_id,$password){
		if (!$user_id && !$password) {
			$this->error = '原始用户UID和原密码不能为空';
			return false;
		}
		$user = $this->where(array('member_id'=>$user_id))->find();
		
		if (md5(md5($password).$user['member_salt']) === $user['member_password']) {
			return true;
		}else{
			$this->error = '原始密码错误！';
			return false;
		}
	}	
	/**
	 * 自动登录用户
	 * @param  integer $user 用户信息数组
	 */
	private function autoLogin($user){
		/* 更新登录信息 */
		$data = array(
			'member_id'         => $user['member_id'],
			'member_login'           => Db::raw('member_login+1'),
			'member_last_login_time' => time(),
			'member_last_login_ip'   => ip2long(request()->ip()),
		);
		$this->allowField(true)->save($data,['member_id' =>$user['member_id']]);
		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'member_id'             => $user['member_id'],
			'member_name'        => $user['member_name'],
			'member_nickname'        => !$user['member_nickname'] ? $user['member_nickname'] : $user['member_name'],
			'member_email'        => $user['member_email'],
			'member_groupid'  => $user['member_groupid'],
			'member_last_login_time' => $user['member_last_login_time'],
		);
		session('member_auth', $auth);
		session('member_auth_sign', data_auth_sign($auth));
	}	
	//获取用户资料
	public function get_user_info(){
		if(member_login()){
			$session=session('member_auth');
			$where=[];
			$where['member_id']=$session['member_id'];
		    $user = db('member')->where($where)->find();
		    if($user){
			    return $user;
		    }else{
		        return false;
		    }
		}else{
		    return false;
		}	
	}
}
// +----------------------------------------------------------------------
// | ZanPianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpiancms.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.zanpiancms.cc>
// +----------------------------------------------------------------------
?>